﻿using AutoMapper;
using System.Linq;
using Paperless.Entities;
using Paperless.Models;
using Paperless.Repositories;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http;
using System.Net.Http;
using Paperless.Results;

namespace Paperless.Controllers
{
    public class TransactionController : BaseApiController<Transaction, TransactionModel>
    {
        public TransactionController(IRepository<Transaction> repository) : base(repository) { }

        public override IHttpActionResult Get()
        {
            var entities = Repository.DbSet();
            var totalCount = entities.Count();

            TransactionSearchModel model;

            if (Request.RequestUri.TryReadQueryAs<TransactionSearchModel>(out model))
            {
                if (!string.IsNullOrEmpty(model.Name))
                {
                    entities = entities.Where(x => x.Name.Contains(model.Name));
                }

                if (!string.IsNullOrEmpty(model.Ascendings) || !string.IsNullOrEmpty(model.Descendings))
                {
                    if (!string.IsNullOrEmpty(model.Ascendings))
                    {
                        var ascendings = model.Ascendings.Split(',');

                        if (ascendings.Contains("name"))
                        {
                            entities = entities.OrderBy(x => x.Name);
                        }

                        if (ascendings.Contains("closeDate"))
                        {
                            entities = entities.OrderBy(x => x.CloseDate);
                        }

                    }

                    if (!string.IsNullOrEmpty(model.Descendings))
                    {
                        var descendings = model.Descendings.Split(',');

                        if (descendings.Contains("name"))
                        {
                            entities = entities.OrderByDescending(x => x.Name);
                        }

                        if (descendings.Contains("closeDate"))
                        {
                            entities = entities.OrderByDescending(x => x.CloseDate);
                        }
                    }
                }
                else
                {
                    entities = entities.OrderByDescending(x => x.UpdatedDate).ThenByDescending(x => x.CreatedDate);
                }

                if (model.Count.HasValue && model.Page.HasValue)
                {
                    entities = entities
                        .Skip(model.Count.Value * (model.Page.Value - 1))
                        .Take(model.Count.Value);
                }               
            }

            return Request.CreateSearchResult<TransactionModel>(entities, totalCount);
        }
    }
}
